export class Line {
    x0: number = 0;
    y0: number = 0;
    x1: number = 0;
    y1: number = 0;
    constructor(x0: number, y0: number, x1: number, y1: number) {
        this.x0 = x0;
        this.y0 = y0;
        this.x1 = x1;
        this.y1 = y1;
    }
    set(x0: number, y0: number, x1: number, y1: number) {
        this.x0 = x0;
        this.y0 = y0;
        this.x1 = x1;
        this.y1 = y1;
    }
    // 求相交的交点
    public lineLine(line: Line): cc.Vec2 {
        let res: cc.Vec2 = cc.v2();
        let x1 = this.x0,
            y1 = this.y0,
            x2 = this.x1,
            y2 = this.y1,
            x3 = line.x0,
            y3 = line.y0,
            x4 = line.x1,
            y4 = line.y1
            ;

        // 由点斜式 y - y0 = k * (x - x0) 可得看k1 k2
        let k1 = (y2 - y1) / (x2 - x1),
            k2 = (y4 - y3) / (x4 - x3);
        // 测试的
        // res.x = (k2 * (x3 - y3) - k1 * (x1 + y1)) * (k2 - k1);
        // res.y = (k2 * (x1 + y1) - k1 * (x3 - y3)) * (k2 - k1);
        // res.y = k2 * res.x;

        // // 正确的
        res.x = ((x2 - x1) * (x3 - x4) * (y3 - y1) - x3 * (x2 - x1) * (y3 - y4) + x1 * (y2 - y1) * (x3 - x4)) / ((y2 - y1) * (x3 - x4) - (x2 - x1) * (y3 - y4));
        res.y = ((y2 - y1) * (y3 - y4) * (x3 - x1) - y3 * (y2 - y1) * (x3 - x4) + y1 * (x2 - x1) * (y3 - y4)) / ((x2 - x1) * (y3 - y4) - (y2 - y1) * (x3 - x4));
        return res;
    }
    // 是否相交
    public isIntersect(line: Line): boolean {
        let res: boolean = false;
        let p0 = cc.v2(this.x0, this.y0)
        let p1 = cc.v2(this.x1, this.y1)
        let p2 = cc.v2(line.x0, line.y0)
        let p3 = cc.v2(line.x1, line.y1)
        function ccw(a, b, c) {
            let v1, v2, v;
            v1 = b.sub(a);
            v2 = c.sub(a);
            v = v1.cross(v2);
            return v;
        }
        if (ccw(p0, p1, p2) * ccw(p0, p1, p3) < 0
            && ccw(p2, p3, p0) * ccw(p2, p3, p1) < 0
        ) {
            res = true;
        }
        return res;
    }
}
